package cn.dapeng.varHandle;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;

/**
 * VarHandle 可以对属性做一些原子性的操作 -- CAS compare and set
 *
 * 比反射快，直接操纵二进制码
 */
public class VarHandle_T01 {

    int x = 8;

    private final static VarHandle handle;

    static {
        try {
            handle = MethodHandles.lookup().findVarHandle(VarHandle_T01.class, "x", int.class);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        VarHandle_T01 varHandle = new VarHandle_T01();

        System.out.println(handle.get(varHandle));
        handle.set(varHandle, 10);
        System.out.println(varHandle.x);

        handle.compareAndSet(varHandle, 10, 20);
        System.out.println(varHandle.x);

        handle.getAndAdd(varHandle, 10);
        System.out.println(varHandle.x);

    }
}
